<script setup>
import { ElMessage } from "element-plus";
import {reactive, ref, onMounted, watch} from "vue"
import {userLoginService, userLogOutService, updatePassword, getUserCurrent,getAwardNum} from '@/api/user'
import { ArrowDown } from '@element-plus/icons-vue'
import { useUserStore } from "@/store/modlues/user/user.js";
import { useRouter } from "vue-router";
import {useRoute} from "vue-router";
import eventBus from "@/main.js";
const route =useRoute()
const dialogFormVisible = ref(false);
const formLabelWidth = '140px';
const show=ref(false)
const userStore = useUserStore()
let userData=ref(userStore.user)
const router=useRouter()
let awardNum=ref(0)
let workListStatus=ref(0)

//切换登录状态 true是未登录
//***********
//
const showLogin=ref(true);
const teacherRole=ref(true);
const judgeRole=ref(true);
//***********
const username=ref('');
// 页面刷新判断是否登录
onMounted(()=>{
  if(userStore.user===''||userStore.user===undefined || userStore.user===null){
    showLogin.value=true
  }else {
    userData.value=userStore.user
    username.value=userStore.user.userName
    showLogin.value=true
  }
  pathShow()
  isAdmin()
  eventBus.on('message-updated', (newMessage) => {
    workListStatus.value=newMessage
  });
})
const isAdmin=()=>{
  if (userData.value === '' || userData.value === undefined) {
    teacherRole.value=true
    judgeRole.value=true
  }
  if(userData.value.userRole==='judge'){
    teacherRole.value=false
  }
  if(userData.value.userRole==='teacher'){
    judgeRole.value=false
  }
}


const form=reactive({
  userAccount: "",
  userPassword: ""
})

//弹出登录框
function isLogin() {
  if(showLogin.value){
    show.value=true
  }
}
const pathOptions=[
  {
    value:"1",
    label:['/index']
  },
  {
    value:"2",
    label:['/guide']
  },
  {
    value:"3",
    label:['/winList']
  },
  {
    value:"4",
    label:['/worksList']
  },
  {
    value:"5",
    label:['/register_1','/register_2']
  },
  {
    value:"6",
    label:['/judges','/scores']
  }
]
const indexValue=ref()
const pathShow=()=>{
  pathOptions.forEach((ops)=>{
    ops.label.forEach(s => {
      if(s===route.path){
        indexValue.value=ops.value
      }
    })
  })
}

//登录
//上传登录数据
const addData=async ()=>{
  const  res=await userLoginService(form)
  if(res.code===200){
    ElMessage.success(res.msg? res.msg:"登录成功");
    show.value=false
    userStore.setToken(res.data)
    const userInfo=await getUserCurrent()
    userStore.setUser(userInfo.data)
    userStore.setToken(res.data)
    userData.value=userStore.user
    await getAward()
    isAdmin()
    showLogin.value=false
  }else {
    ElMessage.error(res.msg)
  }
}
const getAward=async ()=>{
   const res = await getAwardNum()
   if(res.code===200&&res.data.length>0){
     awardNum.value=res.data
   }
}

//校验弹框框输入
const rules={
  userAccount:[
    {required:true,message:'请输入用户名',trigger: 'blur'}
  ],
  userPassword:[
    {required:true,message:'请输入密码',trigger: 'blur'}
  ],
  oldPassword:[
    {required:true,message:'请输入旧密码',trigger: 'blur'}
  ],
  newPassword:[
    {required:true,message:'请输入新密码',trigger: 'blur'}
  ],
  newPasswordConf:[
    {required:true,message:'请输入新密码',trigger: 'blur'}
  ],

};
const isUserInfo=()=>{
  if(userStore.getUser()===null||userStore.getUser()===undefined||userStore.getUser()===''){
    router.replace("/")
  }
}
isUserInfo()
//登出
const LogOut = ()=>{
  //"Logout"为封装的退出登录请求函数
  userLogOutService().then(res=>{
    if(res.code===200){
      showLogin.value=true;
      userStore.removeUser();
      userStore.removeToken();
      userData.value=''
      ElMessage.success(res.msg? res.msg:"已退出登录");
      isAdmin()
      router.replace("/")
    }else{
      ElMessage.success(res.errMsg? res.errMsg:"退出失败")
    }
  }).catch((err)=>{
    showLogin.value=true;
    userStore.removeUser();
    userStore.removeToken();
    userData.value=''
    ElMessage.success("已退出登录");
    isAdmin()
    router.replace("/")
  })
};

//修改密码

const updateForm=reactive({
  oldPassword: "",
  newPassword: "",
  newPasswordConf:""
})

const showUpdatePassword=ref(false)

const update= async ()=>{
  if (updateForm.newPassword.length==0 || updateForm.oldPassword.length==0 || updateForm.newPasswordConf.length==0){

  } else if(updateForm.newPassword!==updateForm.newPasswordConf){
    ElMessage.error('请输入相同密码')
  }else if(updateForm.newPassword===updateForm.oldPassword){
    ElMessage.error('与旧密码相同，请重新修改')
  }else{
    //修改密码
    let res=await updatePassword(updateForm);
    ElMessage.success(res.message);
    LogOut();
    showUpdatePassword.value=false;
  }
};
const toJudge=()=>{
  if(userData.value.userRole==='judge'){
    router.replace('/judges')
  }
  if(userData.value.userRole==='teacher'){
    ElMessage.warning("教师无法进行评审")
    return
  }
  console.log(userData.value.userRole)
  if(userData.value===''){
    show.value=true
  }
}
const application=()=>{
  if(userData.value.userRole==='teacher'){
    router.replace('/register_1')
  }
  if(userData.value.userRole==='judge'){
    ElMessage.warning("评委无法报名")
    return
  }
  if(userData.value===''){
    show.value=true
  }
}
const close=()=>{
  show.value=false
  pathShow()
}


</script>


<template>
  <div id="app">
    <div class="top">
      <text class="title">青岛市中等职业学校教学能力大赛</text>
      <div class="menu">
        <el-menu
            ellipsis
            class="el-menu-popper-demo"
            mode="horizontal"
            style="width: 800px"
            text-color="#000000"
            active-text-color="#426FFF"
            :default-active="indexValue"
        >

          <el-menu-item index="1" class="titleButtonBox" style="padding-top: 8px">
            <router-link to="/index"  class="top-text" style="width: 70px"><text style="margin-left: 17px;color: black">首页</text></router-link>
          </el-menu-item>
          <el-menu-item index="2" class="titleButtonBox" style="padding-top: 8px">
            <router-link to="/guide"  class="top-text" style="width: 90px" ><text style="margin-left: 13px;color: black">比赛指南</text></router-link>
          </el-menu-item>
          <el-menu-item index="3" v-if="workListStatus!==0">
            <router-link to="/worksList"  class="top-text" style="margin-top: 7px" active-class="active">作品展示</router-link>
          </el-menu-item>
          <el-menu-item index="4" class="titleButtonBox" v-if="awardNum!==0">
            <router-link  to="/winList"  class="top-text"  style="margin-top: 7px" active-class="active">
              <text style="margin-left: 12px;margin-right:12px;color: black">获奖名单</text>
            </router-link>
          </el-menu-item>
          <el-menu-item   v-if="teacherRole" index="5" style="padding-left: 0px;padding-right: 0px;">
            <el-text class="top-text" style="width: 100px" @click="application">
              <text style="margin-left: 22px">我要报名</text>
            </el-text>
          </el-menu-item>
          <el-menu-item v-if="judgeRole"  index="6" style="padding-left: 0px;padding-right: 0px">
            <el-text class="top-text" style="width: 120px;border: black 0px solid" @click="toJudge">
              <text style="margin-left: 18px">进入专家评审</text>
            </el-text>
          </el-menu-item>
        </el-menu>
      </div>

      <!-- 登录按钮 -->
      <div>
        <div class="top-button" v-if="showLogin">
          <el-row class="mb-4">
            <el-button type="primary" @click.native="isLogin()">登录</el-button>
          </el-row>
        </div>
        <!-- 转换 用户图标 -->
        <div  style="display: flex;flex-direction: row;" v-else>
          <div class="userIcon" style="z-index:1">
            <el-avatar :size="size" :src="'https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'" />
          </div>
          <div class="dropdown">
            <el-dropdown trigger="click">
                            <span class="el-dropdown-link">
                            {{userStore.user.userName }}
                            <el-icon class="el-icon--right">
                                <arrow-down />
                            </el-icon>
                            </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item @click="showUpdatePassword = true">
                    <svg style="width: 1em; height: 1em;margin-right: 10px;" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" data-v-ea893728=""><path fill="currentColor" d="m199.04 672.64 193.984 112 224-387.968-193.92-112-224 388.032zm-23.872 60.16 32.896 148.288 144.896-45.696zM455.04 229.248l193.92 112 56.704-98.112-193.984-112-56.64 98.112zM104.32 708.8l384-665.024 304.768 175.936L409.152 884.8h.064l-248.448 78.336zm384 254.272v-64h448v64h-448z"></path></svg>
                    <text>修改密码</text>
                  </el-dropdown-item>
                  <el-dropdown-item @click="LogOut()">
                    <svg style="width: 1em; height: 1em;margin-right: 10px;" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024" data-v-ea893728=""><path fill="currentColor" d="M352 159.872V230.4a352 352 0 1 0 320 0v-70.528A416.128 416.128 0 0 1 512 960a416 416 0 0 1-160-800.128z"></path><path fill="currentColor" d="M512 64q32 0 32 32v320q0 32-32 32t-32-32V96q0-32 32-32"></path></svg>
                    <text>退出</text>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>
    </div>

    <div>
      <router-view></router-view>
    </div>


    <!-- 修改密码框 -->
    <el-dialog v-model="showUpdatePassword" title="修改密码" style="width:500px;border-radius: 3%;top: 80px;" >
      <el-form :model="updateForm" :rules="rules">
        <el-form-item label="旧密码" :label-width="formLabelWidth" prop="oldPassword">
          <el-input style="width: 230px" v-model="updateForm.oldPassword" autocomplete="off" placeholder="请输入" />
        </el-form-item>
        <el-form-item  label="新密码" :label-width="formLabelWidth" prop="newPassword">
          <el-input style="width: 230px" v-model="updateForm.newPassword" autocomplete="off"  placeholder="请输入"/>
        </el-form-item>
        <el-form-item label="新密码" :label-width="formLabelWidth" prop="newPasswordConf">
          <el-input style="width: 230px" v-model="updateForm.newPasswordConf" autocomplete="off"  placeholder="请再次输入"/>
        </el-form-item>
      </el-form>
      <template #footer>
            <span class="dialog-footer">

                <el-button @click="showUpdatePassword = false" style="margin-right: 5px;width: 70px;">取消</el-button>
                <el-button type="primary" @click="update()" style="width: 70px;margin-right: 70px;">
                确定
                </el-button>
            </span>
      </template>
    </el-dialog>
    <!-- 登录框 -->
    <el-dialog v-model="show" title="欢迎登录！" style="width:500px;border-radius: 3%;top: 80px;" :before-close="close" >
      <el-form :model="form" :rules="rules">
        <el-form-item label="用户名" :label-width="formLabelWidth" prop="userAccount">
          <el-input style="width: 230px" v-model="form.userAccount" autocomplete="off" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" prop="userPassword">
          <el-input show-password  style="width: 230px" v-model="form.userPassword" autocomplete="off"  placeholder="请输入">

          </el-input>
        </el-form-item>
      </el-form>
      <template #footer>
            <span class="dialog-footer">
                <el-button type="primary" @click="dialogFormVisible = false;addData()">
                登录
                </el-button>
            </span>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>

.titleButtonBox{

  padding-right: 0px;
  padding-left: 0px;
}



.dropdown{

  margin-left: 10px;
  margin-top: 20px;
}

.userIcon{
  margin-top: 10px;
  margin-left: 50px;
}


.example-showcase .el-dropdown-link {

  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}

.dialog-footer button:first-child {
  margin-right: 40%;
  width: 100px;
}





.menu{

  width: 580px;
}
.top{

  display: flex;
  width: 100%;
  height: 60px;
}

.title{
  font-weight: bold;
  width: 300px;
  color: #426FFF;
  font-size: 20px;
  margin-top: 15px;
  margin-left: 15%;
  margin-right: 35px;
}

.el-menu-popper-demo{
  transform: rotateX(180deg);
}

.top-text{
  color: black;
  transform: rotateX(180deg);
  height: 55px;
}

.top-button{

  margin-top: 15px;
  margin-left: 50px;
}

.index1{
  width: 100%;
  height: 100%;

}

a:link {color:#000000;}
a:visited {color:#000000;}
a:hover {background-color:#F5F7F9;color: #678afd;}

</style>